<template>
  <div>
    <div class="row mb-1">
      <div class="col">
        <el-button @click="start" type="primary">查询</el-button>
        <el-button @click="addVipUser" type="primary">添加</el-button>
      </div>
    </div>
    <el-table
      class="margin-top20"
      :data="tableData"
      height="73vh"
      style="width: 100%"
      @sort-change="sortchange"
    >
      <el-table-column prop="ID" sortable="custom" label="ID"></el-table-column>
      <el-table-column prop="userid" label="用户ID"></el-table-column>
      <el-table-column prop="user.name" label="用户名称"></el-table-column>
      <el-table-column
        prop="vipauthority.name"
        label="分组名称"
      ></el-table-column>
      <el-table-column
        prop="vipauthority.description"
        label="分组描述"
      ></el-table-column>
      <el-table-column
        prop="createdAt"
        sortable="custom"
        :formatter="({ createdAt }) => formatter(createdAt)"
        label="创建时间"
      >
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" @click="update(row)" size="default"
            >修改</el-button
          >
          <el-button type="danger" @click="del(row)" size="default"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pager"
      @current-change="handleCurrentChange"
      :page-size="Number(limit)"
      :page-sizes="pageSizes"
      @size-change="handleSizeChange"
      layout="total, sizes ,prev, pager, next"
      :total="totalCount"
    >
    </el-pagination>

    <el-dialog title="" v-model="dialogVisible" width="650" @closed="resetFrom">
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          {{ updateVipUserForm.ID ? "修改" : "添加" }}
        </span>
      </template>
      <el-form
        size="default"
        :model="updateVipUserForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="选择用户">
          <div
            class="user-container cu"
            @click="selectUserDialogVisible = true"
          >
            <el-avatar
              :size="48"
              :src="updateVipUserForm?.user?.headportrait"
            ></el-avatar>
            <div class="margin-left20">
              <el-text type="primary">
                {{ updateVipUserForm?.user?.name }}
              </el-text>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="选择分组">
          <el-select
            v-model="updateVipUserForm.vipauthorityid"
            placeholder="请选择分组"
            size="default"
          >
            <el-option
              v-for="item in allGroup"
              :key="item.ID"
              :label="item.name"
              :value="Number(item.ID)"
            />
          </el-select>
        </el-form-item>
        <div class="row">
          <div class="col text-right">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
          </div>
        </div>
      </el-form>
      <!-- 用户选择 -->
      <el-dialog width="80vw" title="" v-model="selectUserDialogVisible">
        <template #header>
          <span class="icon-text el-dialog__header-title">
            <el-icon class="text-primary">
              <Guide />
            </el-icon>
            选择用户
          </span>
        </template>
        <User
          :userhandleCurrentChange="userhandleCurrentChange"
          :tablekey="selectarr"
        >
        </User>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { inject, onMounted, ref } from "vue";
import {
  asyncdeluservip,
  asyncselectuservip,
  asyncSelectVipAuthority,
  asyncselectviplist,
  asyncupdateuservip,
} from "../../../api/index";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { toLocaleDateString } from "../../../util/time";
import User from "../User/index.vue";

// 码客行
const tenant_id = inject<string | undefined>("tenant_id", undefined);

interface VipUserForm extends Studycodemodel.Iuservip {
  user?: {
    ID?: number;
    name?: string;
    headportrait?: string;
  };
}
const defaultVipUserForm = {
  ID: undefined,
  viplistid: 1,
  vipauthorityid: undefined,
  user: {
    ID: undefined,
    name: "",
    headportrait: "",
  },
};

const limit = ref(20);
const offset = ref(0);
const pageSizes: number[] = [limit.value, 50, 100, 200];
const _sortable = ref<"DESC" | "ASC" | null>("DESC");
const _order = ref(["ID"]);
const tableData = ref<Studycodemodel.Iuservip[]>([]);
const totalCount = ref(0);
const viplist = ref<Studycodemodel.Iviplist[]>([]);
async function start() {
  const list = await asyncselectviplist({ _limit: 10000 });
  viplist.value = list.rows;
  try {
    let z: [keyof Studycodemodel.Iuservip, any] | undefined;
    const data = await asyncselectuservip({
      _limit: limit.value,
      _offset: offset.value,
      _sortable: _sortable.value || "DESC",
      _order: _order.value || ["ID"],
      tenant_id,
    });
    tableData.value = data.rows;
    totalCount.value = data.count;
  } catch (e: any) {
    ElMessage.error(e);
  }
}
onMounted(() => {
  start();
});

function handleCurrentChange(val: number) {
  offset.value = limit.value * (val - 1);
  start();
}
const handleSizeChange = (val: number) => {
  limit.value = val;
  start();
};
function formatter(updatedAt: string) {
  return toLocaleDateString(updatedAt);
}
function sortchange(row: {
  column: any;
  prop: string;
  order: "ascending" | "descending" | null;
}) {
  const { prop, order } = row;
  if (order === "descending") {
    _sortable.value = "DESC";
  } else if (order === "ascending") {
    _sortable.value = "ASC";
  } else {
    _sortable.value = null; // 没有排序
  }
  _order.value = [prop]; // 每次只排序一个字段
  start();
}
// 添加
const selectUserDialogVisible = ref(false);
function userhandleCurrentChange(data: Studycodemodel.Iuser) {
  // 判空
  if (!data) {
    return;
  }
  console.log("userhandleCurrentChange=>", data);
  updateVipUserForm.value.user = {
    ID: data.ID,
    name: data.name,
    headportrait: data.headportrait,
  };
  selectUserDialogVisible.value = false;
}
const selectarr: Array<keyof Studycodemodel.Iuser> = ["name", "ID"];

const dialogVisible = ref(false);
const updateVipUserForm = ref<VipUserForm>({ ...defaultVipUserForm });
const allGroup = ref<Studycodemodel.Ivipauthority[]>([]);
const getAllGroup = async () => {
  const { rows, count } = await asyncSelectVipAuthority({
    _sortable: "DESC",
    _order: ["ID"],
    tenant_id,
  });
  allGroup.value = rows;
};
const addVipUser = () => {
  dialogVisible.value = true;
  getAllGroup();
};

async function submit() {
  try {
    // ID, userid, viplistid, vipauthorityid
    console.log(updateVipUserForm.value);
    await asyncupdateuservip({
      ID: updateVipUserForm.value.ID,
      userid: updateVipUserForm.value.user?.ID,
      viplistid: updateVipUserForm.value.viplistid,
      vipauthorityid: updateVipUserForm.value.vipauthorityid,
      tenant_id,
    });
    ElMessage({ message: "操作成功", type: "success" });
    start();
    dialogVisible.value = false;
  } catch (e: any) {
    ElMessage({ message: e, type: "error" });
  }
}
const resetFrom = () => {
  updateVipUserForm.value = { ...defaultVipUserForm };
  dialogVisible.value = false;
  console.log("updateVipUserForm=>", updateVipUserForm.value);
};

// 修改
const update = async (row: Studycodemodel.Iuservip) => {
  dialogVisible.value = true;
  updateVipUserForm.value = {
    ...row,
    vipauthorityid: row.vipauthorityid ? row.vipauthorityid : undefined,
  };
  getAllGroup();
};
async function del(row: Studycodemodel.Iuservip) {
  ElMessageBox.confirm("确定要删除此用户", "警告", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
  })
    .then(async () => {
      try {
        await asyncdeluservip(row);
        ElMessage({ message: "删除成功", type: "success" });
        start();
      } catch (e) {
        ElMessage({ message: String(e), type: "error" });
      }
    })
    .catch(() => {
      ElMessage({ type: "info", message: "已取消" });
    });
}
</script>

<style scoped>
.user-container {
  display: flex;
  align-items: center;
}
</style>
